/**
 * 单个收费类型
 */
import React, { Component } from 'react';
import { Button, Input, Select, Icon, Popconfirm, Checkbox, Radio, message } from 'antd';

const Option = Select.Option;
const RadioGroup = Radio.Group;

export const defaultValue = {
	name: '',
	showEnable: false,
	vendor: 1,
	param: 1
};

const styles = {
  input: {
    display: 'inline-block',
    width: '4em',
    margin: '0 0.5em'
  },
  select: {
    width: '14em',
    marginRight: '0.5em'
  },
  name: {
    display: 'inline-block',
    width: '12em'
  },
  m: {
    marginRight: '27px'
  },
  h: {
    marginBottom: '0.5em'
  },
  title: {
    fontSize: '18px'
  },
  box: {
    border: '1px solid #ccc',
    borderRadius: '4px',
    marginBottom: '1em'
  },
  save: {
    marginTop: '0.5em',
    textAlign: 'right'
  },
  margin: {
    marginRight: '0.5em'
  },
  span: {
    margin: '0 0.8em'
  },
  icon: {
    fontSize: '16px',
    float: 'right',
    margin: '0 0.4em'
  }
};

function getName(value, arr) {
	const target = arr.find(o => o.value === value);
	return target ? target.name : '未知';
}

class ThirdConfigurationItem extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      ...defaultValue,
      ...props.data,
      edit: !props.data.id
    };
	}

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.setStateFromProps(nextProps);
    }
  }

  setStateFromProps(props) {
    this.setState(Object.keys(defaultValue).reduce((p, k) => {
      p[k] = props.data[k];
      return p;
    }, {}));
  }

  inputChange = e => {
    const { special } = this.state;
    const { name, value } = e.target;
    if (name === 'name') this.setState({ name: value });
    else {
      this.setState({ special: { ...special, [name]: value } });
    }
  }

  specialChange = name => {
    const { dataPoint } = this.props;
    const point = dataPoint.find(d => d.identityName === name);
    let valueLimit = null;
    try {
      valueLimit = JSON.parse(point.valueLimit);
    } catch (error) {
      valueLimit = {
        min: 0,
        max: 50
      };
    }
    const newSpecial = {
      displayUnit: '',
      multiplyValue: '',
      name,
      type: point.dataType,
      min: valueLimit.min,
      max: valueLimit.max,
      step: 1,
      dataPointUnit: ''
    };
    this.setState({ special: { ...newSpecial } });
  }

  delete = () => {
    const { data } = this.props;
    this.props.delete(data.id);
  }

  pointChange = (dataId) => {
		console.log(dataId);
    this.setState({
      dataId,
    });
  }

  paramChange = (e) => {
    this.setState({
      param: e.target.value,
    });
  }

  save = () => {
    const { data, save } = this.props;
    const { special, name, clockCorrectDatapoint, isClockCorrect, showEnable, vendor, param, dataId } = this.state;
    const newData = {
      name, showEnable, vendor, param, dataId,
      id: data.id,
    };
    // if (!name) return message.error('名称为必填项');
    // if (!special.multiplyValue || !special.name || !special.step) return message.error('设置换算单位');
    // if (isClockCorrect && !clockCorrectDatapoint) {
    //   return message.error('请选择换算数据点单位');
    // }
    save(newData);
    this.setState({ edit: false });
  }

  cancel = () => {
    const { data, cancel, index } = this.props;
    this.setStateFromProps(this.props);
    if (data.id) this.setState({ edit: false });
    else cancel(index);
  }

  render() {
    const {
			normal, special, deviceModel, edit, name, id, showEnable, param, vendor, dataId,
		} = this.state;
    const { dataPoint, data, params, vendors } = this.props;
		const uintWritableDataPoint = dataPoint.filter(d => d.dataType.indexOf('uint') === 0 && d.readWriteType === 'status_writable');
    return edit ? (
      <div style={styles.box} className="pad1">
        <div style={styles.h}>
          <label>指令名称：</label>
          <Input style={styles.name} onChange={this.inputChange} name="name" value={name} />
          <Checkbox style={{ marginLeft: '1em' }} checked={showEnable} onChange={e => this.setState({ showEnable: e.target.checked })}>需要展示</Checkbox>
        </div>

        <div style={styles.h}>选择数据点：</div>
        <div style={styles.h}>
          <Select onChange={this.pointChange} value={dataId} style={styles.select}>
            {uintWritableDataPoint.map(d => <Option value={d.id}>{d.identityName}</Option>)}
          </Select>
        </div>
        <div style={styles.h}>
          数据获取方式:<br />
          <Select style={{ width: 120 }} value={vendor} onChange={(e) => this.setState({ vendor: e })}>
						{vendors.map(v => (<Option value={v.value} key={v.value}>{v.name}</Option>))}
          </Select>
        </div>
        <div style={styles.h}>
          对应参数:<br />
          <RadioGroup onChange={this.paramChange} value={param}>
						{params.map(p => (<Radio value={p.value} key={p.value}>{p.name}</Radio>))}
          </RadioGroup>
        </div>
        <hr />
        <div style={styles.save}>
          <Button onClick={this.cancel} style={styles.margin}>取消</Button>
          <Button onClick={this.save} type="primary">保存</Button>
        </div>
      </div>
    ) : (
        <div style={styles.box}>
          <div style={styles.h} className="table-thead pad1">
            <span>{data.name}</span>
            <Popconfirm title="确定删除当前第三方配置吗？" onConfirm={this.delete} okText="确定" cancelText="取消">
              <Icon type="delete" className="cursor" style={styles.icon} />
            </Popconfirm>
            <Icon type="edit" className="cursor" style={styles.icon} onClick={() => this.setState({ edit: true })} />
          </div>
          <div className="pad1">
            <div style={styles.h}>
              <Checkbox
                style={{ marginLeft: '1em' }}
                disabled
                onChange={e => this.setState({ showEnable: e.target.checked })}
              >需要展示</Checkbox>
            </div>
            <div style={styles.h}>
              数据获取方式：{getName(data.vendor, vendors)}
            </div>
            <div style={styles.h}>
              对应参数：{getName(data.param, params)}
            </div>
          </div>
        </div>
      );
  }
}

export default ThirdConfigurationItem;
